//
// Created by 86150 on 2021/11/16.
//

#include <iostream>
#include <mysql.h>
#include "db_manager.h"

db_manager::db_manager()
{
	mysql_init(&mysql);

	if (mysql_real_connect(&mysql, "localhost", "root", "g170411", "test", 3306, NULL, 0))
		std::cout<<"\n Data base init success.\n";
	else
		error("init fail!");
}
void db_manager::insert_usr(std::string name)
{
	if ( query_usr(name) ) return;
	std::string query = "insert into usr (name, times) values " + std::string("") + "(\"" +
			name + "\"," + std::string(" 0") + ")";

	mysql_query(&mysql, query.c_str());
}
void db_manager::add_srcipt(std::string name, std::string kind)
{
	std::string query = "insert into recyclist (name, kind) values" + std::string(" ") +
			"(\"" + name + "\",  \"" + kind + "\")";
	mysql_query(&mysql, query.c_str());
}
int db_manager::count_all(std::string table_name)
{
	std::string query1 = "select * from " + table_name;
	mysql_query(&mysql, query1.c_str());
	res_buf = *mysql_store_result(&mysql);

	int cnt = 0;
	while (mysql_fetch_row(&res_buf) != NULL) cnt++;
	return cnt;
}
void db_manager::update_usr_cnt(std::string name)
{
	if (!query_usr(name)) insert_usr(name);
	std::string query1 = "select * from usr where name=\"" + name + "\"";

	mysql_query(&mysql, query1.c_str());
	res_buf = *mysql_store_result(&mysql);
	row_buf = mysql_fetch_row(&res_buf);

	int now = std::atoi(row_buf[1]);
	std::string query2 = "update usr set times=" + std::to_string(++now) +" where name=\"" +
			std::string(row_buf[0]) + "\"";
	mysql_query(&mysql, query2.c_str());
}
bool db_manager::query_usr(std::string name)
{
	std::string query = "select * from usr where name=\"" + name + "\"";

	mysql_query(&mysql, query.c_str());
	res_buf = *mysql_store_result(&mysql);
	row_buf = mysql_fetch_row(&res_buf);
	if (row_buf == NULL) return false;
	else return true;
}
void db_manager::get_all(std::map<std::string, int>& results)
{
	std::string query = "select * from usr";
	mysql_query(&mysql, query.c_str());
	res_buf = *mysql_store_result(&mysql);

	while ((row_buf = mysql_fetch_row(&res_buf)) and row_buf != NULL) {
		results.insert({std::string(row_buf[0]), int(row_buf[1])});
	}
}
db_manager::~db_manager()
{
	mysql_close(&mysql);
}
void db_manager::error(std::string info)
{
	std::cout<<"DB Error: "<<info<<std::endl;
	exit(-1);
}
